package queue;

import java.util.LinkedList;

/**
 * @description: 20. 有效的括号
 * https://leetcode.cn/problems/valid-parentheses/description/
 * @author: caoyihong
 * @date: 2025-10-11 11:35
 * @Version 1.0
 **/
public class ValidParentheses {

    public boolean isValid(String s) {
        LinkedList<Character> list = new LinkedList<>();
        if (s == null) return true;
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c == '(' || c == '[' || c == '{') {
                // 入栈
                list.addFirst(c);
            } else if (c==')' || c==']' || c=='}') {
                // 查看栈顶元素
                Character peekFirst = list.peekFirst();
                if (peekFirst == null) {
                    return false;
                } else {
                    // 获取栈顶元素
                    Character first = list.removeFirst();
                    if (c==')') {
                        if (first == '(') {
                            continue;
                        } else {
                            return false;
                        }
                    }
                    if (c==']') {
                        if (first == '[') {
                            continue;
                        } else {
                            return false;
                        }
                    }
                    if (c=='}') {
                        if (first == '{') {
                            continue;
                        } else {
                            return false;
                        }
                    }
                }

            }
        }
        if (list.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}
